package com.province.platform.core;

import com.province.platform.common.utils.Configuration;
import com.province.platform.core.job.JobContainer;
import com.province.platform.core.constants.CoreConstants;
import com.province.platform.core.utils.ConfigParser;
import com.province.platform.core.utils.ConfigurationValidate;
import com.province.platform.core.utils.LoadUtils;
import org.apache.commons.cli.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

public class Platform {
    private static final Logger LOG = LoggerFactory.getLogger(Platform.class);

    public static void entry(String[] args) throws Throwable {
        Options options = new Options();
        options.addOption("id", true, "unique id.");
        options.addOption("config", true, "config.");

        // 解析配置
        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = parser.parse(options, args);
        String id = commandLine.getOptionValue("id");
        String configPath = commandLine.getOptionValue("config");

        Configuration configuration = ConfigParser.parse(configPath);
        configuration.set(CoreConstants.CORE_CONTAINER_JOB_ID, id);

        LOG.info("\n" + filterJobConfiguration(configuration));
        LOG.debug(configuration.toJSON());

        ConfigurationValidate.doValidate(configuration);
        Platform platform = new Platform();
        platform.start(configuration);
    }

    public void start(Configuration configuration) {
        /**
         * 初始化PluginLoader，可以获取各种插件配置
         */
        LoadUtils.bind(configuration);

        AbstractContainer container = new JobContainer(configuration);
        container.start();
    }

    public static String filterJobConfiguration(final Configuration configuration) {
        Configuration config = configuration.getConfiguration("job").clone();
        Configuration jobContent = config.getConfiguration("content");
        filterSensitiveConfiguration(jobContent);
        config.set("content", jobContent);
        return config.beautify();
    }

    public static Configuration filterSensitiveConfiguration(Configuration configuration) {
        Set<String> keys = configuration.getKeys();
        for (final String key: keys) {
            boolean isSensitive = StringUtils.endsWithIgnoreCase(key, "password");
            if (isSensitive && configuration.get(key) instanceof String) {
                configuration.set(key, configuration.getString(key).replace(".", "*"));
            }
        }
        return configuration;
    }

    public static void main(String[] args) {
        int exitCode = 0;

        try {
            Platform.entry(args);
        } catch (Throwable e) {
            exitCode = 1;
            System.exit(exitCode);
        }
        System.exit(exitCode);
    }
}
